<template>
  <div class='container'>
    <el-dialog
      :title="showTitle"
      :visible='showDialog'
      @close='closeDialog'
      :close-on-click-modal='false'
    >
      <el-form
        ref="deptForm"
        label-width="120px"
        :model="form"
        :rules="rules"
      >
        <el-form-item
          label="学科名称"
          prop="subjectName"
        >
          <el-input
            v-model="form.subjectName"
            style="width:80%"
            placeholder="请输入学科名称"
          />
        </el-form-item>
        <el-form-item label="是否显示">
          <el-switch
            v-model="form.isFrontDisplay"
            active-color="#13ce66"
            inactive-color="#ff4949"
            active-value='1'
            inactive-value='0'
          >
          </el-switch>
        </el-form-item>
      </el-form>
      <template v-slot:footer>
        <el-button
          size="small"
          @click="closeDialog"
        >取消</el-button>
        <el-button
          type="primary"
          size="small"
          @click='yesDialog'
        >确认</el-button>
      </template>
    </el-dialog>
  </div>

</template>

<script>
//
import { subjectAddAPI, subjectUpdateAPI } from '@/api/hmmm/subjects'
export default {
  name: 'SubjectsAdd',
  data() {
    return {
      showTitle: '',
      form: {
        subjectName: '',
        isFrontDisplay: '1'
      },
      rules: {
        subjectName: [{ required: true, message: '学科名称不可为空', trigger: 'blur' }]
      }
    }
  },
  props: {
    showDialog: {
      type: Boolean,
      default: false
    }
  },
  methods: {
    /**
     * 点击x号和取消，关闭弹框
     */
    closeDialog() {
      // 关闭弹框
      this.$emit('update:showDialog', false)
      // 清空弹框数据（绑定了prop表单数据的）
      this.$refs.deptForm.resetFields()
      this.form.isFrontDisplay = '1'
    },
    yesDialog() {
      // 先进行统一校验
      this.$refs.deptForm.validate(async flag => {
        if (flag) {
          if (this.showTitle === '修改名称') {
            await subjectUpdateAPI(this.form)
            // 添加成功校验
            this.$message.success('恭喜，修改成功')
          } else if (this.showTitle === '添加名称') {
            // 可以进行表单提交
            this.form.isFrontDisplay = '1'
            await subjectAddAPI(this.form)
            // 添加成功校验
            this.$message.success('恭喜，添加成功')
          }
          // 添加成功关闭弹框
          this.closeDialog()
          // 重新获取数据列表 组件在父组件中，看组件套的层级，基层就写几个$parent
          this.$parent.subjectList()
        }
      })
    }
  }
}
</script>

<style scoped lang='less'></style>
